package extract.helper;

import common.config.VendorTypes;
import common.dao.mysql.MySqlDao;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.tools.cmd.gen.AnyVals;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by julianzliu on 2017/1/5.
 */
public class DocUploadHelper {
    public static final Logger logger = LoggerFactory.getLogger(DocUploadHelper.class);

    private MySqlDao mysqldao;
    private Connection conn;

    private String upload_db = "upload_log";
    private String couchid_tb = "json_couch_ids";
    private String upload_tb = "upload_log";

    private String material_db = "tps";
    private String material_tb = "material";

    public DocUploadHelper(MySqlDao dao){
        this.mysqldao = dao;
        this.conn = this.mysqldao.getCon();
    }

    @Override
    protected void finalize(){
        try {
            super.finalize();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        this.mysqldao.closeCon();
    }

    public String getUploadIdByCouchId(String couch_id, String couch_type){
        logger.debug("[getUploadIdByCouchId] couch_id = {}, couch_type = {}" , couch_id, couch_type);
        String sql = String.format(
                "select log_id from %s.%s where couch_id = '%s' order by id desc limit 1;",
                this.upload_db, this.couchid_tb, couch_id
        );
        logger.debug("[getUploadIdByCouchId] sql = \n{}", sql);
        int upload_id = -1;
        int index = 0;
        try{
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                upload_id = rs.getInt("log_id");
                index += 1;
            }
            stmt.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(index == 0)
            logger.error("[getUploadIdByCouchId] no result found!");
        return Integer.toString(upload_id);
    }

    public Map<String,String> getUploadRecordByUploadId(String upload_id){
        String sql = String.format(
                "select vendor_name, vendor_path, video_copyright, material_id from %s.%s where log_id=%s limit 1; ",
                this.upload_db, this.upload_tb, upload_id
        );
        logger.debug("[getUploadRecordByUploadId] sql = \n{}", sql);
        Map<String,String> ret = new HashMap<>();
        int index = 0;
        try{
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                ret.clear();
                String vendor_name = rs.getString("vendor_name");
                String vendor_path = rs.getString("vendor_path");
                String video_copyright = rs.getString("video_copyright");
                String material_id = Integer.toString( rs.getInt("material_id") );
                ret.put("vendor_name", vendor_name);
                ret.put("vendor_path", vendor_path);
                ret.put("video_copyright", video_copyright);
                ret.put("material_id", material_id);
                index += 1;
            }
            stmt.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(index == 0)
            logger.error("[getUploadRecordByUploadId] no result dound!");
        return ret;
    }

    public int getVendorType(Map<String,String> ret){
        String vendor_name = "";
        if(ret.containsKey("vendor_name"))
            vendor_name = ret.get("vendor_name");
        int vendor_type = VendorTypes.enterpri;
        if(vendor_name.equals(VendorTypes.personal_str)){
            vendor_type = VendorTypes.personal;
        }
        return vendor_type;
    }

    public String getMaterialId(Map<String,String> ret){
        String material_id = "-1";
        if(ret.containsKey("material_id")){
            material_id = ret.get("material_id");
        }
        return material_id;
    }

    public Map<String,String> getMaterialRecordByMaterialId(String material_id){
        String sql = String.format(
                "select mType,media_type from %s.%s where id=%s limit 1;",
                this.material_db, this.material_tb, material_id
        );
        logger.debug("[getMaterialRecordByMaterialId] sql = \n{}", sql);

        Map<String,String> ret = new HashMap<>();
        int index = 0;
        try{
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                ret.clear();
                String resource_type = rs.getString("mType");
                String media_type = rs.getString("media_type");
                ret.put("resource_type", resource_type);
                ret.put("media_type", media_type);
                index += 1;
            }
            stmt.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(index == 0)
            logger.error("[getUploadRecordByUploadId] no result dound!");
        return ret;
    }

    public String parseResourceTypeOfPersonal(Map<String,String> ret){
        //Map<String,String> ret = getMaterialRecordByMaterialId( material_id );
        String type = null;
        if(ret.containsKey("resource_type") ){
            String resource_type = ret.get("resource_type");
            if(resource_type.equals("full")){
                type = "成片";
            }
            else if(resource_type.equals("material")){
                type = "素材";
            }
            else {
                type = "成片 素材 未知";
            }
        }
        else{
            type = "未知";
        }
        return type;
    }

    public String parseResourceTypeOfEnterprise(Map<String,String> ret){
        String type = "未知";
        return type;
    }

    public String parseResourceType(int vendor_type, String material_id){
        Map<String,String> ret = getMaterialRecordByMaterialId( material_id );
        String resource_type = parseResourceTypeOfEnterprise( ret );
        if(vendor_type == VendorTypes.personal){
            resource_type = parseResourceTypeOfPersonal( ret );
        }
        else if(vendor_type == VendorTypes.enterpri){
            resource_type = parseResourceTypeOfEnterprise( ret );
        }
        return resource_type;
    }

    public String parseCopyright(Map<String,String> ret){
        String copyright = " 未知 ";
        if(ret.containsKey("video_copyright")){
            copyright = ret.get("video_copyright");
            copyright += " 版权 ";
        }
        return copyright;
    }

    public String parseVideoFormat(Map<String,String> ret){
        String format = " UNKONWN ";
        String vendor_path = "";
        if(ret.containsKey("vendor_path"))
            vendor_path = ret.get("vendor_path");
        logger.debug("[parseVideoFormat] vendor_path = {}", vendor_path);
        String[] parts = vendor_path.split("\\.");
        logger.debug("[parseVideoFormat] parts length = {}", parts.length);
        if(parts.length >= 2)
            format = parts[parts.length - 1];
        return format;
    }

    public Map<String,String> getDocInfoByCouchId(String couch_id, String couch_type){
        String upload_id = getUploadIdByCouchId(couch_id, couch_type);
        logger.debug("upload_id = " +  upload_id);

        Map<String,String> upload_record = getUploadRecordByUploadId( upload_id );

        String copyright = parseCopyright(upload_record);
        logger.debug("copyright = " + copyright);

        String format = parseVideoFormat(upload_record);
        logger.debug("video_format = " + format);

        int vendor_type = getVendorType( upload_record );
        logger.debug("vendor_type = " + vendor_type);

        String material_id = getMaterialId( upload_record );
        logger.debug("material_id = " + material_id);

        String resource_type = parseResourceType(vendor_type, material_id );
        logger.debug("resource_type = " + resource_type);



        Map<String, String> result = new HashMap<>();
        result.put("copyright", copyright);
        result.put("resource_type", resource_type);
        result.put("vendor_type", Integer.toString(vendor_type));
        result.put("video_format", format);
        return result;
    }

    public static void  test(){
        String str = "vendor_path = /home/luyj/AccessServer/data/upload/video/北京您早 2015-04-20（二）0809333800000.wmv";
        String[] parts = str.split("\\.");
        System.out.println(parts.length);
        System.out.println(parts[parts.length-1]);
    }


    /***********************
     * main test
     */
    public static void main(String[] args){
        DocUploadHelper docUploadHelper = new DocUploadHelper( new MySqlDao() );


        //String couch_id = "6fcba0fd5073fcb5841cfa659e002089";
        String couch_id = "1";
        couch_id = "6fcba0fd5073fcb5841cfa659e0094f5";
        //couch_id = "6fcba0fd5073fcb5841cfa659e002089";
        String couch_type = "program";

        /*
        String upload_id = docUploadHelper.getUploadIdByCouchId(couch_id, couch_type);
        System.out.println("upload_id = " +  upload_id);

        Map<String,String> upload_record = docUploadHelper.getUploadRecordByUploadId( upload_id );

        String copyright = docUploadHelper.parseCopyright(upload_record);
        System.out.println("copyright = " + copyright);


        int vendor_type = docUploadHelper.getVendorType( upload_record );
        System.out.println("vendor_type = " + vendor_type);

        String material_id = docUploadHelper.getMaterialId( upload_record );
        System.out.println("material_id = " + material_id);

        String resource_type = docUploadHelper.parseResourceType(vendor_type, material_id );
        System.out.println("resource_type = " + resource_type);
        */


        Map<String,String> result = docUploadHelper.getDocInfoByCouchId( couch_id, couch_type);
        System.out.println("copyright = " + result.get("copyright"));
        System.out.println("resource_type = " + result.get("resource_type"));

        test();


    }


}
